package spring.security.maven.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import spring.security.maven.util.FileTools;
import spring.security.maven.util.SecurityTools;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Created by Server on 2015/5/23.
 */
@Controller
@RequestMapping("/admin")
public class UploadController {
    /***
     * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
     * @paramfile
     * @return
     */
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request) {
        // 判断文件是否为空
        String name= SecurityTools.getUserName();
        System.out.println("用户名字："+name+"--------long->"+files);
        for (int i = 0; i <files.length; i++) {

        if (!files[i].isEmpty()) {
            try {
                // 文件保存路径
                File filepath=new File(request.getSession().getServletContext().getRealPath("/") + "upload/"+name+"/");
                if(!filepath.exists()){
                    filepath.mkdirs();
                    System.out.println("创建成功:"+filepath.getAbsolutePath());
                }
                String filePath = filepath.getAbsolutePath()+"\\"
                        + files[i].getOriginalFilename();
                System.out.println("路径：" + filePath);
                FileTools f=new FileTools();
                files[i].transferTo(new File(f.isExists(filePath)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        }
        // 重定向
        return "success";
    }

    /***
     * 读取上传文件中得所有文件并返回
     *
     * @return
     */
    @RequestMapping("/upload")
    public String  toUpload(HttpServletRequest request) {
//        String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
//        ModelAndView mav = new ModelAndView("list");
//        File uploadDest = new File(filePath);
//        String[] fileNames = uploadDest.list();
//        for (int i = 0; i < fileNames.length; i++) {
//            //打印出文件名
//            System.out.println(fileNames[i]);
//        }
        System.out.println("_csrf:"+request.getAttribute("_csrf"));
        return "/admin/upload";
    }
}
